<template>
  <div ref="dom" class="charts chart-bar"></div>
</template>

<script>
import echarts from 'echarts'
import tdTheme from './theme.json'
import { on, off } from '@/libs/tools'
echarts.registerTheme('tdTheme', tdTheme)
export default {
  name: 'ChartBar',
  props: {
    value: Array,
    text: String
  },
  data () {
    return {
      dom: null,
      xAxisData: null,
      socialSecurityData: null,
      providentFundData: null,
      commercialInsuranceData: null
    }
  },
  watch: {
    value: {
      handler (val, oldVal) {
        this.value = val
        this.initBar()
      },
      deep: true
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.initBar()
    })
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    initBar () {
      let xAxisData = this.value.map(item => {
        return item.month
      })
      let socialSecurityData = this.value.map(item => {
        return item.socialSecurity
      })
      let providentFundData = this.value.map(item => {
        return item.providentFund
      })
      let commercialInsuranceData = this.value.map(item => {
        return item.commercialInsurance
      })
      let option = {
        title: {
          text: this.text,
          textStyle: {
            color: '#333'
          },
          x: 'left'
        },
        legend: {
          data: ['month', '社保', '公积金', '商保'],
          bottom: '2%'
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {},
        series: [
          {
            name: '社保',
            type: 'bar',
            data: socialSecurityData,
            itemStyle: {
              normal: {
                color: '#0dc2ff',
                label: {
                  show: true, // 开启显示
                  position: 'top',
                  color: '#0dc2ff'
                }
              }
            }
          },
          {
            name: '公积金',
            type: 'bar',
            data: providentFundData,
            itemStyle: {
              normal: {
                color: '#ffc858',
                label: {
                  show: true, // 开启显示
                  position: 'top',
                  color: '#ffc858'
                }
              }
            }
          },
          {
            name: '商保',
            type: 'bar',
            data: commercialInsuranceData,
            itemStyle: {
              normal: {
                color: '#aa7fff',
                label: {
                  show: true, // 开启显示
                  position: 'top',
                  color: '#aa7fff'
                }
              }
            }
          }
        ]
      }
      this.dom = echarts.init(this.$refs.dom, 'tdTheme')
      this.dom.setOption(option)
      on(window, 'resize', this.resize)
    }
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  }
}
</script>
